import os
import subprocess
from loguru import logger
import time

def execute_sh(cmd):
    logger.info(cmd)
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    logger.debug(type(p))
    logger.debug(p)
    for line in iter(p.stdout.readline, b''):
        line = line.strip().decode("utf-8")
        logger.debug(line)


def get_app_paths(directory):
    app_paths = []
    for root, dirs, files in os.walk(directory):
        # 第一层目录
        if root == directory:
            logger.debug(f"root: {root}")
            logger.debug(f"dirs: {dirs}")
            # 判断有没有node_modules文件夹
            for dir in dirs:
                if not os.path.exists(os.path.join(root, dir, "node_modules")):
                    app_paths.append(os.path.join(root, dir))
                    logger.debug(f"files: {os.path.join(root, dir)}")
                    logger.debug(f"files: {files}")
    return app_paths

def print_app_paths():
    child_apps_directory = './child_apps'
    main_apps_directory = './main_apps'

    child_app_paths = get_app_paths(child_apps_directory)
    main_app_paths = get_app_paths(main_apps_directory)
    logger.debug(f"Child Apps Paths:{child_app_paths}")
    logger.debug(f"Main Apps Paths:{main_app_paths}")

    logger.debug("Child Apps Paths:")
    for path in child_app_paths:
        logger.debug(path)

    logger.debug("\nMain Apps Paths:")
    for path in main_app_paths:
        logger.debug(path)

def sh_single_path(path):
    # path = path.split("package.json")[0].split("./")[-1]
    # 获取当前目录
    # os.getcwd()
    # from pathlib import Path
    # current_dir = Path.cwd()
    #  os.path.dirname(os.path.abspath(sys.argv[0]))
    # import inspect
    # os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    # path = os.path.join(os.getcwd(), path)
    logger.debug(f"执行命令: cd {path} && pnpm install")
    execute_sh(f"cd {path} && pnpm install")
    time.sleep(20)
    if not os.path.exists(os.path.join(path, 'node_modules')):
        while os.path.exists(os.path.join(path, 'node_modules')):
            logger.debug("等待node_modules安装完成")
            time.sleep(10)
    logger.debug("{path} 安装完成!")

def install_dependencies():
    # 遍历child_apps目录和main_apps目录，拿到该路径
    child_apps_directory = os.path.join(os.getcwd(), 'child_apps')
    main_apps_directory = os.path.join(os.getcwd(), 'main_apps')

    child_app_paths = get_app_paths(child_apps_directory)
    main_app_paths = get_app_paths(main_apps_directory)
    logger.debug(f"Child Apps Paths:{child_app_paths}")
    logger.debug(f"Main Apps Paths:{main_app_paths}")
    for path in child_app_paths:
        logger.debug(f"拼接的路径：{path}")
        sh_single_path(path)
    for path in main_app_paths:
        logger.debug(f"拼接的路径：{path}")
        sh_single_path(path)

def single_install_dependencies():
    path = f"E:/Desktop/front-learn/micro-app-demo/child_apps/vite-vue3/"
    execute_sh(f"cd {path} && pnpm install") # yarn 有网络问题
    time.sleep(10)
    while os.path.exists(os.path.join(path, 'node_modules')):
            logger.debug("等待node_modules安装完成")
            time.sleep(10)
    logger.debug("安装完成")


# print_app_paths()
# single_install_dependencies()
if __name__ == '__main__':
    # install_dependencies()
    print_app_paths()
    
